<?php

namespace app\admin\controller\communityclasses;

use app\common\controller\Backend;
use think\Db;

/**
 * 社区班级管理
 *
 * @icon fa fa-users
 */
class Communityclasses extends Backend
{

    /**
     * CommunityClasses模型对象
     */
    protected $model = null;
    protected $noNeedRight = '*';
    protected $noNeedLogin = [];

    public function _initialize()
    {
        parent::_initialize();

        // 确保加载admin模块的common.php文件
        if (is_file(APP_PATH . 'admin/common.php')) {
            include_once APP_PATH . 'admin/common.php';
        }

        // 设置正确的视图路径
        $this->view->config('view_path', APP_PATH . 'admin/view/');

        // 禁用模板缓存以避免缓存问题
        $this->view->config('tpl_cache', false);

        // 强制设置中文语言
        \think\Lang::range('zh-cn');

        // 加载通用语言包
        \think\Lang::load(APP_PATH . 'admin/lang/zh-cn.php');

        // 直接加载控制器语言包
        $langFile = APP_PATH . 'admin/lang/zh-cn/communityclasses/communityclasses.php';
        if (file_exists($langFile)) {
            \think\Lang::load($langFile);
        }

        $this->model = model('app\admin\model\OcationClass');
        $this->modelValidate = true;

        // 确保表结构包含社区班级所需字段
        $this->ensureSchema();
    }

    /**
     * 自动补齐 fa_ocation_class 字段
     */
    protected function ensureSchema()
    {
        $table = config('database.prefix') . 'ocation_class'; // fa_ocation_class
        $columns = Db::query("SHOW COLUMNS FROM `{$table}`");
        $existing = array_column($columns, 'Field');

        $alterSql = [];
        if (!in_array('classes_type', $existing)) {
            $alterSql[] = "ADD COLUMN `classes_type` TINYINT(3) NOT NULL DEFAULT 2 COMMENT '班级类型：1报名 2预约/社区'";
        }
        if (!in_array('manager_id', $existing)) {
            $alterSql[] = "ADD COLUMN `manager_id` INT(11) NOT NULL DEFAULT 0 COMMENT '班级管理员ID'";
        }
        if (!in_array('open_apply', $existing)) {
            $alterSql[] = "ADD COLUMN `open_apply` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否开放申请加入'";
        }
        if (!in_array('need_verify', $existing)) {
            $alterSql[] = "ADD COLUMN `need_verify` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '加入是否需要验证'";
        }
        if (!in_array('show_in_team_list', $existing)) {
            $alterSql[] = "ADD COLUMN `show_in_team_list` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否在班级团队列表呈现'";
        }
        if (!in_array('allow_members_view', $existing)) {
            $alterSql[] = "ADD COLUMN `allow_members_view` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '成员是否可查看详情'";
        }
        if (!in_array('qrcode', $existing)) {
            $alterSql[] = "ADD COLUMN `qrcode` VARCHAR(255) DEFAULT NULL COMMENT '班级二维码地址'";
        }

        if (!empty($alterSql)) {
            $sql = "ALTER TABLE `{$table}` " . implode(', ', $alterSql);
            try {
                Db::execute($sql);
            } catch (\Exception $e) {
                // 忽略重复添加或无权限错误
            }
        }
    }

    /**
     * 查看
     */
    public function index()
    {
        // 设置JavaScript配置
        $this->assignconfig('jsname', 'backend/communityclasses/communityclasses');
        $this->assignconfig('actionname', 'index');
        $this->assignconfig('controllername', 'communityclasses/communityclasses');
        $user= $this->auth->getUserInfo();


        // 传递语言包数据给前端
        $langData = [
            'Id' => __('Id'),
            'Class Number' => __('Class Number'),
            'Class Name' => __('Class Name'),
            'Teaching Point Name' => __('Teaching Point Name'),
            'Manager ID' => __('Manager ID'),
            'Open Application' => __('Open Application'),
            'Show in Team List' => __('Show in Team List'),
            'Class Avatar' => __('Class Avatar'),
            'Create Time' => __('Create Time'),
            'Operate' => __('Operate'),
            'Yes' => __('Yes'),
            'No' => __('No'),
            'None' => __('None'),
        ];
        $this->assignconfig('lang', $langData);

        // 确保权限变量可用
        $this->assign('auth', $this->auth);

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 创建额外的查询条件数组
            $extraWhere = [];

            // 根据用户组进行数据过滤
            $admin = [];
            if (isset($_SESSION['think']['admin']) && is_array($_SESSION['think']['admin'])) {
                $admin = $_SESSION['think']['admin'];
            }

            if (!empty($admin['group_id'])) {
                if ($admin['group_id'] == 3) { // 学校管理用户
                    if (!empty($admin['school_id'])) {
                        $extraWhere[] = ['oc.school_id', 'like', '%' . $admin['school_id'] . '%'];
                    }
                } elseif ($admin['group_id'] == 8) { // 社区管理用户
                    if (!empty($admin['city_id'])) {
                        $extraWhere[] = ['oc.city_id', 'like', '%' . $admin['city_id'] . '%'];
                    }
                }
            }

            $query = $this->model->alias('oc')
                ->join(config('database.prefix') . 'ocation o', 'o.id = oc.ocation_id', 'LEFT')
                ->where("oc.ocation_id","=",$user['ocation_id'])
                ->field('oc.*, o.name as ocation_name')
                ->where($where);

            // 添加额外的查询条件
            if (!empty($extraWhere)) {
                foreach ($extraWhere as $condition) {
                    if (is_array($condition) && count($condition) >= 3) {
                        $query->where($condition[0], $condition[1], $condition[2]);
                    }
                }
            }

            $total = $query->order("oc.weigh asc")->order($sort, $order)->count();

            $list = $this->model->alias('oc')
                ->join(config('database.prefix') . 'ocation o', 'o.id = oc.ocation_id', 'LEFT')
                ->where("oc.ocation_id","=",$user['ocation_id'])
                ->field('oc.*, o.name as ocation_name')
                ->where($where);

            // 添加额外的查询条件
            if (!empty($extraWhere)) {
                foreach ($extraWhere as $condition) {
                    if (is_array($condition) && count($condition) >= 3) {
                        $list->where($condition[0], $condition[1], $condition[2]);
                    }
                }
            }

            $list = $list->order("oc.weigh asc");

            // 只有当排序字段不是 weigh 时，才添加额外的排序
            if ($sort != 'weigh') {
                $list = $list->order($sort, $order);
            }

            $list = $list->limit($offset, $limit)
                ->select();

            // 在转换为数组前处理时间字段，防止 strtotime 警告
            $list = $this->processListTimeFields($list);

            $list = collection($list)->toArray();
            if (is_array($list)) {
                foreach ($list as $i => $item) {
                    if (is_array($item)) {
                        // 获取格式化序号
                        $list[$i]['formatted_sequence'] = \app\admin\model\OcationClass::getFormattedSequence($item['sequence_number'] ?? 0);

                        // 处理封面图片
                        if (!empty($item['cover'])) {
                            $list[$i]['cover'] = createImg($_SERVER['DOCUMENT_ROOT'] . '/' . $item['cover'], '220', '220');
                        }

                        // 获取管理员名称
                        if (!empty($item['manager_id'])) {
                            $admin = \think\Db::name('admin')->where('id', $item['manager_id'])->find();
                            $list[$i]['manager_name'] = $admin ? $admin['nickname'] : '';
                        } else {
                            $list[$i]['manager_name'] = '';
                        }

                        // 获取班级类型文本
                        $list[$i]['class_type_text'] = $this->getClassTypeText($item['class_type'] ?? 1);
                    }
                }
            }
            $result = array("total" => $total, "rows" => $list);



            return json($result);
        }

        return $this->view->fetch('communityclasses/communityclasses/index');
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $user= $this->auth->getUserInfo();
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
//                    if ($this->modelValidate) {
//                        $validate = new \app\admin\validate\OcationClass();
//                        if (!$validate->scene('add')->check($params)) {
//                            return json(['code' => 0, 'msg' => $validate->getError()]);
//                        }
//                    }

                    $params['status'] = 1;
                    $currentTime = date('Y-m-d H:i:s');
                    $params['create_time'] = $currentTime;
                    $params['update_time'] = $currentTime;
                    $params['sequence_number'] = \app\admin\model\OcationClass::getNextSequence();
                    $params['ocation_id'] = $user['ocation_id'];
                    $params['classes_type'] = 2;
                    // 过滤和处理时间字段
                    $this->filterTimeFields($params, $currentTime);

                    // 自动插入session中的城市和学校ID
                    $admin = [];
                    if (isset($_SESSION['think']['admin']) && is_array($_SESSION['think']['admin'])) {
                        $admin = $_SESSION['think']['admin'];
                    }
                    if (!empty($admin['city_id'])) {
                        $params['city_id'] = $admin['city_id'];
                    }
                    if (!empty($admin['school_id'])) {
                        $params['school_id'] = $admin['school_id'];
                    }

                    // 检查是否已存在相同 ocation_id 和相同名称的记录
                    $existingRecord = $this->model->where('ocation_id', $user['ocation_id'])
                        ->where('name', $params['name'])
                        ->find();

                    if ($existingRecord) {
                        // 存在相同教学点和相同名称的记录，更新现有记录
                        $params['update_time'] = date('Y-m-d H:i:s');
                        // 保留原有的创建时间和序号
                        unset($params['create_time']);
                        unset($params['sequence_number']);

                        // 过滤和处理时间字段
                        $this->filterTimeFields($params, date('Y-m-d H:i:s'));

                        // 生成二维码（如果需要）
                        if (empty($params['qrcode']) && empty($existingRecord['qrcode'])) {
                            $params['qrcode'] = $this->generateQrcode($params);
                        }

                        // 临时禁用自动时间戳，因为我们手动设置了时间
                        $existingRecord->isAutoWriteTimestamp(false);
                        $result = $existingRecord->allowField(true)->save($params);
                        $message = '更新成功';
                    } else {
                        // 不存在相同记录，直接新增（允许同一教学点有多个不同名称的班级）
                        // 生成二维码
                        if (empty($params['qrcode'])) {
                            $params['qrcode'] = $this->generateQrcode($params);
                        }

                        // 临时禁用自动时间戳，因为我们手动设置了时间
                        $this->model->isAutoWriteTimestamp(false);
                        $result = $this->model->allowField(true)->save($params);
                        $message = '添加成功';
                    }

                    if ($result !== false) {
                        return json_encode(['code' => 1, 'msg' => $message]);
                    } else {
                        return json(['code' => 0, 'msg' => $this->model->getError()]);
                    }
                } catch (\think\exception\PDOException $e) {
                    return json(['code' => 0, 'msg' => $e->getMessage()]);
                } catch (\think\Exception $e) {
                    return json(['code' => 0, 'msg' => $e->getMessage()]);
                }
            }
            return json(['code' => 0, 'msg' => __('Parameter %s can not be empty', '')]);
        }

        // 设置管理员配置信息到前端
        $user = $this->auth->getUserInfo();
        $this->assignconfig("admin", [
            'id' => $user['id'],
            'username' => $user['username'],
            'city_id' => $user['city_id'] ?? '',
            'school_id' => $user['school_id'] ?? '',
            'rel_type' => $user['rel_type'] ?? '',
            'rel_id' => $user['rel_id'] ?? '',
            'group_id' => $user['group_id'] ?? ''
        ]);

        // 设置JavaScript配置和语言包
        $this->assignconfig('jsname', 'backend/communityclasses/communityclasses');
        $this->assignconfig('actionname', 'add');
        $this->assignconfig('controllername', 'communityclasses/communityclasses');

        // 为社区管理员设置专门的上传 URL
        $uploadConfig = config('upload');
        $uploadConfig['uploadurl'] = 'communityclasses/communityclasses/upload';
        $this->assignconfig('upload', $uploadConfig);

        return $this->view->fetch('communityclasses/communityclasses/add');
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $user= $this->auth->getUserInfo();
        // 处理不同的参数格式
        if (is_null($ids)) {
            $ids = $this->request->param('ids');
        }
        if (is_null($ids)) {
            $ids = $this->request->param('id');
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
//                    if ($this->modelValidate) {
//                        $validate = new \app\admin\validate\OcationClass();
//                        if (!$validate->scene('edit')->check($params)) {
//                            return json(['code' => 0, 'msg' => $validate->getError()]);
//                        }
//                    }

                    // 检查是否有其他记录使用相同的 ocation_id 和相同的名称（排除当前记录）
                    $params['ocation_id'] = $user['ocation_id'];
                    if (isset($params['ocation_id']) && isset($params['name'])) {
                        $conflictRecord = $this->model->where('ocation_id', $user['ocation_id'])
                            ->where('name', $params['name'])
                            ->where('id', 'neq', $ids)
                            ->find();

                        if ($conflictRecord) {
                            return json(['code' => 0, 'msg' => '该教学点已存在相同名称的班级']);
                        }
                    }

                    $params['update_time'] = date('Y-m-d H:i:s');
                    $params['classes_type'] = 2;
                    // 过滤和处理时间字段
                    $this->filterTimeFields($params, date('Y-m-d H:i:s'));

                    // 如果二维码为空，重新生成
                    if (empty($params['qrcode'])) {
                        $params['qrcode'] = $this->generateQrcode($params);
                    }

                    // 临时禁用自动时间戳，因为我们手动设置了时间
                    $row->isAutoWriteTimestamp(false);
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        return json_encode(['code' => 1, 'msg' => '更新成功']);
                    } else {
                        return json(['code' => 0, 'msg' => $row->getError()]);
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        // 设置管理员配置信息到前端
        $user = $this->auth->getUserInfo();
        $this->assignconfig("admin", [
            'id' => $user['id'],
            'username' => $user['username'],
            'city_id' => $user['city_id'] ?? '',
            'school_id' => $user['school_id'] ?? '',
            'rel_type' => $user['rel_type'] ?? '',
            'rel_id' => $user['rel_id'] ?? '',
            'group_id' => $user['group_id'] ?? ''
        ]);

        // 设置JavaScript配置和语言包
        $this->assignconfig('jsname', 'backend/communityclasses/communityclasses');
        $this->assignconfig('actionname', 'edit');
        $this->assignconfig('controllername', 'communityclasses/communityclasses');

        // 调试：记录配置信息
        file_put_contents(
            $_SERVER["DOCUMENT_ROOT"] . "/../config_debug.log",
            "Edit method config at " . date('Y-m-d H:i:s') . "\n" .
                "Config: " . json_encode($this->view->config) . "\n\n",
            FILE_APPEND
        );

        // 为社区管理员设置专门的上传 URL
        $uploadConfig = config('upload');
        $uploadConfig['uploadurl'] = 'communityclasses/communityclasses/upload';
        $this->assignconfig('upload', $uploadConfig);

        $this->view->assign("row", $row);

        // 临时调试：直接输出模板内容
        $templatePath = 'communityclasses/communityclasses/edit';
        $content = $this->view->fetch($templatePath);

        // 记录调试信息
        file_put_contents(
            $_SERVER["DOCUMENT_ROOT"] . "/../edit_debug.log",
            "Edit method called at " . date('Y-m-d H:i:s') . "\n" .
                "Template path: " . $templatePath . "\n" .
                "Content length: " . strlen($content) . "\n" .
                "Contains form: " . (strpos($content, '<form') !== false ? 'Yes' : 'No') . "\n" .
                "Contains bootstrap-table: " . (strpos($content, 'bootstrap-table') !== false ? 'Yes' : 'No') . "\n" .
                "First 200 chars: " . substr($content, 0, 200) . "\n\n",
            FILE_APPEND
        );

        // 强制设置正确的JavaScript配置到模板变量
        $this->view->assign('Config', [
            'jsname' => 'backend/communityclasses/communityclasses',
            'actionname' => 'edit',
            'controllername' => 'communityclasses/communityclasses',
            'admin' => $this->view->config['admin'] ?? []
        ]);

        return $content;
    }

    /**
     * 删除
     */
    public function del($ids = '')
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            \think\Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                \think\Db::commit();
            } catch (\Exception $e) {
                \think\Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 生成班级二维码
     */
    private function generateQrcode($data)
    {
        // 这里应该调用二维码生成API，暂时返回一个占位符
        $classId = isset($data['id']) ? $data['id'] : uniqid();
        return 'https://ys.yangjc.com/qrcode/class/' . $classId;
    }

    /**
     * 获取班级类型文本
     */
    private function getClassTypeText($type)
    {
        $types = [
            1 => '普通班级',
            2 => '兴趣班级',
            3 => '专业班级',
            4 => '活动班级'
        ];
        return isset($types[$type]) ? $types[$type] : '未知类型';
    }

    /**
     * 更改状态
     */
    public function changeStatus($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result = $this->model->where("id", "=", $ids)->field("status")->find();
            $v = $result->status == 1 ? 0 : 1;
            $this->model->where("id", "=", $ids)->update(["status" => $v]);
            $this->success('切换成功!');
        } catch (\Exception $e) {
            $this->error('切换失败!' . $e->getMessage());
        }
    }

    /**
     * 排序
     */
    public function sort()
    {
        if ($this->request->isPost()) {
            $ids = $this->request->post('ids');
            if ($ids) {
                $arr = explode(',', $ids);
                foreach ($arr as $k => $v) {
                    $this->model->where('id', $v)->update(['weigh' => count($arr) - $k]);
                }
                $this->success();
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 获取教学点列表
     */
    public function getOcationList()
    {
        $admin = $_SESSION['think']['admin'] ?? [];
        $where = ['status' => 1];

        // 根据用户组过滤教学点
        if (isset($admin['group_id'])) {
            if ($admin['group_id'] == 8 && isset($admin['city_id']) && !empty($admin['city_id'])) {
                // 社区管理员只能看到自己城市的教学点
                $where['city_id'] = $admin['city_id'];
            } elseif ($admin['group_id'] == 3 && isset($admin['school_id']) && !empty($admin['school_id'])) {
                // 学校管理员只能看到自己学校的教学点
                $where['school_id'] = $admin['school_id'];
            }
        }

        $list = \think\Db::name('ocation')->where($where)->field('id,name')->select();
        return json(['code' => 1, 'data' => $list]);
    }

    /**
     * 获取管理员列表
     */
    public function getAdminList()
    {
        $admin = $_SESSION['think']['admin'] ?? [];
        $where = ['status' => 'normal'];

        // 根据用户组过滤管理员
        if (isset($admin['group_id'])) {
            if ($admin['group_id'] == 8 && isset($admin['city_id']) && !empty($admin['city_id'])) {
                // 社区管理员只能看到自己城市的管理员
                $where['city_id'] = $admin['city_id'];
            } elseif ($admin['group_id'] == 3 && isset($admin['school_id']) && !empty($admin['school_id'])) {
                // 学校管理员只能看到自己学校的管理员
                $where['school_id'] = $admin['school_id'];
            }
        }

        $list = \think\Db::name('admin')->where($where)->field('id,nickname')->select();
        return json(['code' => 1, 'data' => $list]);
    }

    /**
     * 过滤和处理时间字段，防止 strtotime null 警告
     */
    private function filterTimeFields(&$params, $defaultTime)
    {
        // 过滤掉所有可能为 null 或空字符串的时间相关字段
        $timeFields = ['create_time', 'update_time', 'delete_time'];
        foreach ($timeFields as $field) {
            if (isset($params[$field]) && ($params[$field] === null || $params[$field] === '' || $params[$field] === '0000-00-00 00:00:00')) {
                unset($params[$field]);
            }
        }

        // 确保必要的时间字段有值
        if (!isset($params['create_time']) && strpos($defaultTime, date('Y-m-d')) !== false) {
            $params['create_time'] = $defaultTime;
        }
        if (!isset($params['update_time'])) {
            $params['update_time'] = $defaultTime;
        }

        // 验证时间格式
        foreach (['create_time', 'update_time'] as $field) {
            if (isset($params[$field]) && !preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $params[$field])) {
                $params[$field] = $defaultTime;
            }
        }
    }

    /**
     * 处理查询结果列表中的时间字段，防止 strtotime null 警告
     */
    private function processListTimeFields($list)
    {
        if (!$list) return $list;

        $timeFields = ['create_time', 'update_time', 'delete_time'];

        foreach ($list as $item) {
            if (!$item) continue;

            foreach ($timeFields as $field) {
                if (isset($item->$field)) {
                    $value = $item->$field;
                    // 如果时间字段为 null、空字符串或无效日期，设置为有效的默认值
                    if ($value === null || $value === '' || $value === '0000-00-00 00:00:00') {
                        // 对于 create_time 和 update_time，设置为当前时间
                        // 对于 delete_time，保持为 null
                        if ($field === 'delete_time') {
                            $item->$field = null;
                        } else {
                            $item->$field = date('Y-m-d H:i:s');
                        }
                    }
                    // 如果是无效的时间格式，也进行修正
                    elseif (is_string($value) && !preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $value)) {
                        if ($field === 'delete_time') {
                            $item->$field = null;
                        } else {
                            $item->$field = date('Y-m-d H:i:s');
                        }
                    }
                }
            }
        }

        return $list;
    }

    /**
     * 获取班级成员列表
     */
    public function getClassMembers()
    {
        if (!$this->auth->isLogin()) {
            return json(['code' => 0, 'msg' => '请先登录管理后台']);
        }

        $classId = $this->request->param('class_id');
        if (!$classId) {
            return json(['code' => 0, 'msg' => '班级ID不能为空']);
        }

        try {
            // 获取分页参数
            $page = $this->request->param('page', 1);
            $limit = $this->request->param('limit', 10);
            $offset = ($page - 1) * $limit;
            $sort = $this->request->param('sort', 'create_time');
            $order = $this->request->param('order', 'desc');
            $search = $this->request->param('search', '');

            // 检查eb_class_student表是否存在
            $tableExists = Db::query("SHOW TABLES LIKE 'eb_class_student'");
            if (empty($tableExists)) {
                return json(['code' => 0, 'msg' => 'eb_class_student表不存在', 'total' => 0, 'rows' => []]);
            }

            // 检查表结构，确认classes_id字段是否存在
            $tableStructure = Db::query("SHOW COLUMNS FROM eb_class_student");
            $columns = array_column($tableStructure, 'Field');



            // 确定要使用的字段名
            $possibleFields = ['classes_id', 'class_id', 'classid', 'ocation_class_id', 'ocation_id'];
            $foundField = null;

            foreach ($possibleFields as $field) {
                if (in_array($field, $columns)) {
                    $foundField = $field;
                    break;
                }
            }

            if (!$foundField) {
                return json([
                    'code' => 0,
                    'msg' => 'eb_class_student表中未找到班级ID相关字段',
                    'total' => 0,
                    'rows' => []
                ]);
            }

            // 构建查询对象
            $baseQuery = Db::name('eb_class_student')
                ->alias('cs')
                ->join('fa_user u', 'cs.student_id = u.id', 'LEFT')
                ->field('cs.*, u.username, u.nickname, u.mobile, u.avatar');

            // 添加班级ID条件
            $baseQuery->where('cs.' . $foundField, '=', $classId);

            // 添加状态条件 - 排除已删除的记录 (status = -1)
            $baseQuery->where('cs.status', '>', -1);

            // 排除软删除的记录
            $baseQuery->whereNull('cs.delete_time');

            // 添加搜索条件
            if ($search) {
                $baseQuery->where(function ($query) use ($search) {
                    $query->where('u.username', 'like', '%' . $search . '%')
                        ->whereOr('u.nickname', 'like', '%' . $search . '%')
                        ->whereOr('u.mobile', 'like', '%' . $search . '%');
                });
            }





            // 获取总数
            $total = $baseQuery->count();

            // 获取列表数据
            $list = Db::name('eb_class_student')
                ->alias('cs')
                ->join('fa_user u', 'cs.student_id = u.id', 'LEFT')
                ->field('cs.*, u.username, u.nickname, u.mobile, u.avatar')
                ->where('cs.' . $foundField, '=', $classId)
                ->where('cs.status', '>', -1)  // 排除已删除的记录
                ->whereNull('cs.delete_time');  // 排除软删除的记录

            // 添加搜索条件
            if ($search) {
                $list->where(function ($query) use ($search) {
                    $query->where('u.username', 'like', '%' . $search . '%')
                        ->whereOr('u.nickname', 'like', '%' . $search . '%')
                        ->whereOr('u.mobile', 'like', '%' . $search . '%');
                });
            }

            $list = $list->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            // 处理返回的数据，确保格式正确
            $processedList = [];
            if ($list) {
                foreach ($list as $item) {
                    // 确保所有字段都有值，避免undefined
                    $processedItem = [
                        'id' => intval($item['id'] ?? 0),
                        'student_id' => intval($item['student_id'] ?? 0),
                        'username' => strval($item['username'] ?? ''),
                        'nickname' => strval($item['nickname'] ?? ''),
                        'mobile' => strval($item['mobile'] ?? ''),
                        'avatar' => strval($item['avatar'] ?? ''),
                        'status' => intval($item['status'] ?? 1),
                        'create_time' => strval($item['create_time'] ?? ''),
                    ];

                    // 添加班级ID字段
                    $processedItem[$foundField] = intval($item[$foundField] ?? $classId);

                    // 格式化时间显示
                    if ($processedItem['create_time']) {
                        $processedItem['create_time'] = date('Y-m-d H:i:s', strtotime($processedItem['create_time']));
                    }

                    $processedList[] = $processedItem;
                }
            }

            // 返回标准的bootstrap-table格式
            $result = array(
                "total" => intval($total),
                "rows" => $processedList
            );

            return json($result);
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'msg' => '查询失败：' . $e->getMessage(),
                'total' => 0,
                'rows' => []
            ]);
        }
    }

    /**
     * 添加班级成员
     */
    public function addClassMember()
    {
        if (!$this->auth->isLogin()) {
            return json(['code' => 0, 'msg' => '请先登录管理后台']);
        }

        if ($this->request->isPost()) {
            $classId = $this->request->post('class_id');
            $studentId = $this->request->post('student_id');
            $status = $this->request->post('status', 1); // 默认状态为1（正常）

            if (!$classId || !$studentId) {
                return json(['code' => 0, 'msg' => '班级ID和学员ID不能为空']);
            }

            // 检查是否已存在
            $exists = Db::name('eb_class_student')
                ->where('classes_id', $classId)
                ->where('student_id', $studentId)
                ->find();

            if ($exists) {
                return json(['code' => 0, 'msg' => '该学员已在班级中']);
            }

            // 检查学员是否存在
            $user = Db::name('user')->where('id', $studentId)->find();
            if (!$user) {
                return json(['code' => 0, 'msg' => '学员不存在']);
            }

            try {
                // 检查表结构，获取实际的字段名和类型
                $tableInfo = Db::query("SHOW COLUMNS FROM eb_class_student");
                $fields = [];
                $fieldTypes = [];
                foreach ($tableInfo as $field) {
                    $fields[] = $field['Field'];
                    $fieldTypes[$field['Field']] = $field['Type'];
                }

                $data = [
                    'classes_id' => $classId,
                    'classes_type' => 2,
                    'student_id' => $studentId,
                    'status' => $status
                ];

                // 根据实际字段和类型添加时间字段
                $currentTime = date('Y-m-d H:i:s');
                $currentTimestamp = time();

                // 处理create_time字段
                if (in_array('create_time', $fields)) {
                    if (strpos($fieldTypes['create_time'], 'int') !== false) {
                        $data['create_time'] = $currentTimestamp; // 时间戳格式
                    } else {
                        $data['create_time'] = $currentTime; // datetime格式
                    }
                }

                // 处理add_time字段
                if (in_array('add_time', $fields)) {
                    if (strpos($fieldTypes['add_time'], 'int') !== false) {
                        $data['add_time'] = $currentTimestamp; // 时间戳格式
                    } else {
                        $data['add_time'] = $currentTime; // datetime格式
                    }
                }

                // 处理update_time字段
                if (in_array('update_time', $fields)) {
                    if (strpos($fieldTypes['update_time'], 'int') !== false) {
                        $data['update_time'] = $currentTimestamp; // 时间戳格式
                    } else {
                        $data['update_time'] = $currentTime; // datetime格式
                    }
                }

                // 处理其他可能的时间字段
                if (in_array('createtime', $fields)) {
                    $data['createtime'] = $currentTimestamp; // 通常是时间戳格式
                }
                if (in_array('updatetime', $fields)) {
                    $data['updatetime'] = $currentTimestamp; // 通常是时间戳格式
                }

                Db::name('eb_class_student')->insert($data);
                return json(['code' => 1, 'msg' => '添加成功']);
            } catch (\Exception $e) {
                return json(['code' => 0, 'msg' => '添加失败：' . $e->getMessage()]);
            }
        }
    }



    /**
     * 导出班级成员列表
     */
    public function exportClassMembers()
    {
        if (!$this->auth->isLogin()) {
            return json(['code' => 0, 'msg' => '请先登录管理后台']);
        }

        $classId = $this->request->post('class_id');
        if (!$classId) {
            return json(['code' => 0, 'msg' => '班级ID不能为空']);
        }

        try {
            // 获取班级信息
            $classInfo = $this->model->get($classId);
            if (!$classInfo) {
                return json(['code' => 0, 'msg' => '班级不存在']);
            }

            // 获取成员列表
            $members = Db::name('eb_class_student')
                ->alias('cs')
                ->join('fa_user u', 'cs.student_id = u.id', 'LEFT')
                ->field('cs.*, u.username, u.nickname, u.mobile, u.email')
                ->where('cs.classes_id', $classId)
                ->order('cs.create_time', 'desc')
                ->select();

            // 生成CSV内容
            $csvContent = "\xEF\xBB\xBF"; // UTF-8 BOM
            $csvContent .= "序号,学员ID,用户名,昵称,手机号,邮箱,状态,加入时间\n";

            $statusMap = [
                '0' => '待审批',
                '1' => '正常',
                '2' => '已拒绝'
            ];

            foreach ($members as $index => $member) {
                $csvContent .= ($index + 1) . ',';
                $csvContent .= ($member['student_id'] ?? '') . ',';
                $csvContent .= ($member['username'] ?? '') . ',';
                $csvContent .= ($member['nickname'] ?? '') . ',';
                $csvContent .= ($member['mobile'] ?? '') . ',';
                $csvContent .= ($member['email'] ?? '') . ',';
                $csvContent .= ($statusMap[$member['status']] ?? '未知') . ',';
                $csvContent .= ($member['create_time'] ?? $member['add_time'] ?? '') . "\n";
            }

            // 设置下载头
            $filename = $classInfo['name'] . '_成员列表_' . date('Y-m-d_H-i-s') . '.csv';
            header('Content-Type: application/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename="' . $filename . '"');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Expires: 0');

            echo $csvContent;
            exit;
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '导出失败：' . $e->getMessage()]);
        }
    }

    /**
     * 删除班级成员
     */
    public function removeClassMember()
    {
        try {
            $ids = $this->request->post('ids');
            if (empty($ids)) {
                return json(['code' => 0, 'msg' => '请选择要删除的成员']);
            }

            // 将逗号分隔的字符串转换为数组
            if (is_string($ids)) {
                $ids = explode(',', $ids);
            }

            // 过滤空值
            $ids = array_filter($ids);
            if (empty($ids)) {
                return json(['code' => 0, 'msg' => '请选择要删除的成员']);
            }

            // 检查字段类型，确定时间格式
            $tableInfo = Db::query("SHOW COLUMNS FROM eb_class_student");
            $fieldTypes = [];
            foreach ($tableInfo as $field) {
                $fieldTypes[$field['Field']] = $field['Type'];
            }

            // 准备更新数据
            $updateData = ['status' => -1];
            $currentTime = date('Y-m-d H:i:s');
            $currentTimestamp = time();

            // 根据字段类型设置正确的时间格式
            if (isset($fieldTypes['delete_time'])) {
                if (strpos($fieldTypes['delete_time'], 'int') !== false || strpos($fieldTypes['delete_time'], 'bigint') !== false) {
                    $updateData['delete_time'] = $currentTimestamp; // 时间戳格式
                } else {
                    $updateData['delete_time'] = $currentTime; // datetime格式
                }
            }

            if (isset($fieldTypes['update_time'])) {
                if (strpos($fieldTypes['update_time'], 'int') !== false || strpos($fieldTypes['update_time'], 'bigint') !== false) {
                    $updateData['update_time'] = $currentTimestamp; // 时间戳格式
                } else {
                    $updateData['update_time'] = $currentTime; // datetime格式
                }
            }



            // 执行软删除
            $result = Db::name('eb_class_student')
                ->whereIn('id', $ids)
                ->update($updateData);

            if ($result) {
                return json(['code' => 1, 'msg' => '删除成功，共删除 ' . count($ids) . ' 个成员']);
            } else {
                return json(['code' => 0, 'msg' => '删除失败']);
            }
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 审批班级成员
     */
    public function approveClassMember()
    {
        try {
            $ids = $this->request->post('ids');
            $status = $this->request->post('status', 1); // 默认为通过

            if (empty($ids)) {
                return json(['code' => 0, 'msg' => '请选择要审批的成员']);
            }

            // 将逗号分隔的字符串转换为数组
            if (is_string($ids)) {
                $ids = explode(',', $ids);
            }

            // 过滤空值
            $ids = array_filter($ids);
            if (empty($ids)) {
                return json(['code' => 0, 'msg' => '请选择要审批的成员']);
            }

            // 验证状态值
            if (!in_array($status, [0, 1, 2])) {
                return json(['code' => 0, 'msg' => '无效的审批状态']);
            }

            // 检查字段类型，确定时间格式
            $tableInfo = Db::query("SHOW COLUMNS FROM eb_class_student");
            $fieldTypes = [];
            foreach ($tableInfo as $field) {
                $fieldTypes[$field['Field']] = $field['Type'];
            }

            // 准备更新数据
            $updateData = ['status' => $status];
            $currentTime = date('Y-m-d H:i:s');
            $currentTimestamp = time();

            // 根据字段类型设置正确的时间格式
            if (isset($fieldTypes['update_time'])) {
                if (strpos($fieldTypes['update_time'], 'int') !== false || strpos($fieldTypes['update_time'], 'bigint') !== false) {
                    $updateData['update_time'] = $currentTimestamp; // 时间戳格式
                } else {
                    $updateData['update_time'] = $currentTime; // datetime格式
                }
            }



            // 更新成员状态
            $result = Db::name('eb_class_student')
                ->whereIn('id', $ids)
                ->update($updateData);

            if ($result) {
                $statusText = $status == 1 ? '通过' : ($status == 2 ? '拒绝' : '待审核');
                return json(['code' => 1, 'msg' => '审批成功，共' . $statusText . ' ' . count($ids) . ' 个成员']);
            } else {
                return json(['code' => 0, 'msg' => '审批失败']);
            }
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '审批失败：' . $e->getMessage()]);
        }
    }



    /**
     * 搜索用户
     */
    public function searchUsers()
    {
        try {
            $keyword = $this->request->get('q', '');
            $limit = intval($this->request->get('limit', 20));
            $page = intval($this->request->get('page', 1));
            $offset = ($page - 1) * $limit;

            // 构建基础查询条件
            $baseQuery = Db::name('user')
                ->where('status', 'normal');

            if (!empty($keyword)) {
                $baseQuery->where(function ($query) use ($keyword) {
                    $query->whereOr('username', 'like', '%' . $keyword . '%')
                        ->whereOr('nickname', 'like', '%' . $keyword . '%')
                        ->whereOr('mobile', 'like', '%' . $keyword . '%');
                });
            }

            // 获取总数（不应用limit）
            $total = $baseQuery->count();

            // 获取数据列表（应用limit）
            $list = Db::name('user')
                ->field('id, username, nickname, mobile, avatar')
                ->where('status', 'normal');

            if (!empty($keyword)) {
                $list->where(function ($query) use ($keyword) {
                    $query->whereOr('username', 'like', '%' . $keyword . '%')
                        ->whereOr('nickname', 'like', '%' . $keyword . '%')
                        ->whereOr('mobile', 'like', '%' . $keyword . '%');
                });
            }

            $list = $list->limit($offset, $limit)->select();

            return json([
                'code' => 1,
                'msg' => '查询成功',
                'data' => $list ?: [],
                'total' => $total,
                'count' => count($list ?: []),
                'more' => $total > ($offset + count($list ?: []))
            ]);
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '搜索失败：' . $e->getMessage()]);
        }
    }

    /**
     * 文件上传接口（专门为社区管理员提供）
     */
    public function upload()
    {
        // 直接调用管理后台的上传方法
        $ajax = new \app\admin\controller\Ajax();
        return $ajax->upload();
    }

    /**
     * 获取管理员列表
     */
    public function getUserAdminList()
    {
        try {
            $keyword = $this->request->get('q', '');
            $limit = intval($this->request->get('limit', 50));
            $page = intval($this->request->get('page', 1));
            $offset = ($page - 1) * $limit;

            // 构建查询条件 - 获取所有管理员用户（状态正常的用户）
            $baseQuery = Db::name('user')
                ->where('status', 'normal');

            // 如果有关键词，则进行模糊搜索
            if (!empty($keyword)) {
                $baseQuery->where(function ($query) use ($keyword) {
                    $query->whereOr('username', 'like', '%' . $keyword . '%')
                        ->whereOr('nickname', 'like', '%' . $keyword . '%')
                        ->whereOr('mobile', 'like', '%' . $keyword . '%');
                });
            }

            // 获取总数
            $total = $baseQuery->count();

            // 获取管理员列表数据
            $list = Db::name('user')
                ->field('id, username, nickname, mobile, avatar, email')
                ->where('status', 'normal');

            // 应用搜索条件
            if (!empty($keyword)) {
                $list->where(function ($query) use ($keyword) {
                    $query->whereOr('username', 'like', '%' . $keyword . '%')
                        ->whereOr('nickname', 'like', '%' . $keyword . '%')
                        ->whereOr('mobile', 'like', '%' . $keyword . '%');
                });
            }

            $list = $list->order('id', 'desc')
                ->limit($offset, $limit)
                ->select();

            return json([
                'code' => 1,
                'msg' => '查询成功',
                'data' => $list ?: [],
                'total' => $total,
                'count' => count($list ?: [])
            ]);
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '获取管理员列表失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取管理员信息
     */
    public function getAdminInfo()
    {
        try {
            $adminId = $this->request->get('id', 0);
            
            if (empty($adminId)) {
                return json(['code' => 0, 'msg' => '管理员ID不能为空']);
            }

            // 查询管理员信息
            $admin = Db::name('user')
                ->field('id, username, nickname, mobile, avatar, email')
                ->where('id', $adminId)
                ->where('status', 'normal')
                ->find();

            if (!$admin) {
                return json(['code' => 0, 'msg' => '管理员不存在或已被禁用']);
            }

            return json([
                'code' => 1,
                'msg' => '获取成功',
                'data' => $admin
            ]);
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => '获取管理员信息失败：' . $e->getMessage()]);
        }
    }
}
